import uuid
# 获取字符出现的频数
def count_frequency(input_string):
    # 用于存放字符
    char_store = []
    # 用于存放频数
    freq_store = []

    # 解析字符串
    for index in range(len(input_string)):
        if char_store.count(input_string[index]) > 0:
            temp = int(freq_store[char_store.index(input_string[index])])
            temp = temp + 1
            freq_store[char_store.index(input_string[index])] = temp
        else:
            char_store.append(input_string[index])
            freq_store.append(1)
    # 返回字符列表和频数列表
    return char_store, freq_store

# 获取字符、频数的列表
def get_char_frequency(char_store=[], freq_store=[]):
    # 用于存放char_frequency
    char_frequency = []
    for item in zip(char_store, freq_store):
        temp = (item[0], item[1])
        char_frequency.append(temp)
    return char_frequency

# 将字符转换成huffman编码
def get_huffman_file(input_string, char_frequency, codes):
    # 逐个字符替换
    file_content = ''
    for index in range(len(input_string)):
        for item in zip(char_frequency, codes):
            if input_string[index] == item[0][0]:
                file_content = file_content + item[1]
    file_name = 'huffman_' + str(uuid.uuid1())+'.txt'
    with open(file_name, 'w+') as destination:
        destination.write(file_content)
    return file_name

# 计算压缩比
def get_encode_ration(codes):
    # 计算所需要的二进制个数
    h_length = 0
    for item in codes:
        h_length = h_length + len(item)
    t_length = bin_middle(len(codes))*len(codes)
    ratio = t_length/h_length
    return str(ratio)[0:3]

# 计算所在的二进制空间
def bin_middle(number):
    n, i = 1, 0
    while n < number:
        n = n * 2
        i = i + 1
    return i

# 解压缩huffman文件
def decode_huffman(input_string,  char_store, freq_store):
    encode = ''
    decode = ''
    for index in range(len(input_string)):
        encode = encode + input_string[index]
        for item in zip(char_store, freq_store):
            if encode == item[1]:
                decode = decode + item[0]
                encode = ''
    return decode

# 保存上传的文件
def save_file(file):
    file_name = str(uuid.uuid1())+'.txt'
    with open(file_name, 'wb+') as destination:
        for chunk in file.chunks():
            destination.write(chunk)
    return file_name

# 读取上传的文件
def read_file(file_name):
    file_content = ''
    file = open(file_name, 'r')
    line = file.readline()
    while line:
        file_content = file_content + line
        line = file.readline()
    file.close()
    return file_content

# 读取解码表
def read_code_table(file_name):
    # 用于存放字符
    char_store = []
    # 用于解码字符
    freq_store = []
    file = open(file_name, 'r')
    line = file.readline()
    while line:
        a = line.split(',', 1)
        char_store.append(a[0])
        freq_store.append(a[1])
        line = file.readline()
    file.close()
    return char_store, freq_store

